package com.wjd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjd.common.utils.PageUtils;
import com.wjd.common.utils.Query;
import com.wjd.gulimall.product.dao.CategoryDao;
import com.wjd.gulimall.product.entity.CategoryEntity;
import com.wjd.gulimall.product.service.CategoryBrandRelationService;
import com.wjd.gulimall.product.service.CategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Lazy
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree(Map<String, Object> params) {
        // 1. 查询所有分类
        List<CategoryEntity> categories = this.list(
                new QueryWrapper<CategoryEntity>().orderByAsc("sort", "cat_id"));
        // 2. 构建树形结构
        List<CategoryEntity> level1 = categories.stream()
                .filter(category -> category.getParentCid() == 0)
                .collect(Collectors.toList());
        level1.forEach(category -> buildTree(category, categories));
        // 3. 返回树形结构的分类列表
        return level1;
    }

    /**
     * 构建树形结构
     *
     * @param parent 父分类实体
     * @param categories 所有分类列表
     */
    private void buildTree(CategoryEntity parent, List<CategoryEntity> categories) {
        if (parent == null || categories == null) {
            return;
        }
        List<CategoryEntity> children = categories.stream()
                .filter(category -> category.getParentCid().equals(parent.getCatId()))
                .peek(child -> buildTree(child, categories)) // 递归构建子分类
                .collect(Collectors.toList());
        parent.setChildren(children);
    }

    @Override
    public void removeMenusByIds(List<Long> ids) {
        // TODO 检查是否有其他地方依赖这些商品分类，然后再删除
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public List<Long> getCategoryPath(Long id) {
        List<Long> path = new ArrayList<>();
        Long currentId = id;
        while (currentId != null && currentId > 0) {
            CategoryEntity category = this.getById(currentId);
            if (category == null) {
                break;
            }
            path.add(category.getCatId());
            currentId = category.getParentCid();
        }
        Collections.reverse(path); // 反转路径列表，使其从根到叶子节点
        return path;
    }

    @Transactional
    @Override
    public void updateCategory(CategoryEntity category) {
        // 1. 更新分类信息
        this.updateById(category);
        // 2. 更新关联表中冗余的分类名称
        if (StringUtils.isNotBlank(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

}